package cn.bmbanjia.zebra2024.apps.base.verificationCode.service.impl;

import cn.bmbanjia.zebra2024.apps.meituanMiniApp.satoken.MeituanCurrentUser;
import cn.bmbanjia.zebra2024.apps.meituanMiniApp.satoken.StpMeituanUtil;
import cn.bmbanjia.zebra2024.apps.meituanMiniApp.user.req.CodeReq;
import cn.bmbanjia.zebra2024.frame.exception.CodeException;
import cn.bmbanjia.zebra2024.frame.resp.Resp;
import cn.bmbanjia.zebra2024.wwxy.WwxySendSms;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import cn.bmbanjia.zebra2024.apps.base.verificationCode.entity.VerificationCode;
import cn.bmbanjia.zebra2024.apps.base.verificationCode.mapper.VerificationCodeMapper;
import cn.bmbanjia.zebra2024.apps.base.verificationCode.service.IVerificationCodeService;
import io.netty.handler.codec.CodecException;
import org.springframework.stereotype.Service;

import static cn.bmbanjia.zebra2024.apps.base.verificationCode.entity.table.VerificationCodeTableDef.VERIFICATION_CODE;

/**
 * 短信验证码 服务层实现。
 *
 * @author fugui
 * @since 2024-06-16
 */
@Service
public class VerificationCodeServiceImpl extends ServiceImpl<VerificationCodeMapper, VerificationCode> implements IVerificationCodeService {

    @Override
    public synchronized Resp<Void> sendCode(CodeReq req) {

        long count = count(QueryWrapper.create()
                .where(VERIFICATION_CODE.TELEPHONE.eq(req.getMobile()))
                .where(VERIFICATION_CODE.CREATE_TIME.ge(DateTime.now().offset(DateField.HOUR_OF_DAY, -1).getTime() / 1000)));

        Assert.isTrue(count < 5, () -> new CodecException("验证码发送频繁"));

        String code = RandomUtil.randomNumbers(6);

        MeituanCurrentUser meituanCurrentUser = StpMeituanUtil.currentUser();

        VerificationCode vc = VerificationCode.builder()
                .telephone(req.getMobile())
                .status(0)
                .type(2)
                .code(code)
                .delFlag(false)
                .createTime((int) (DateTime.now().getTime() / 1000))
                .createUserId(meituanCurrentUser.getUserId())
                .createUserName(meituanCurrentUser.getUserNickName())
                .build();

        boolean save = save(vc);
        Assert.isTrue(save, CodeException::new);

        WwxySendSms.sendMsg(req.getMobile(), StrUtil.format("【斑马搬家】验证码{}，您正在进行身份验证，打死不要告诉别人哦！", code));

        return Resp.success();
    }

}
